const QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
// 必填,填完之后就可以调用腾讯地图的一些牛逼的接口或者函数
//在本次例子中运用到了逆解析,将经纬坐标转化成准确的地址
const wxMap = new QQMapWX({
  //申请得到key
  key: 'J2HBZ-GQBC3-5V53S-34NJF-VKCXJ-FEF74' 
});
Page({
  data: {
    //将得到的经纬坐标和准确地址保存在此data中
    longitude: '',
    latitude: '',
    reallAddress: ""
  },
  onLoad() {
    this.Location()
  },
  regionchange(e) {
    // 地图发生变化的时候，获取中间点，也就是用户选择的位置toFixed
    if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
      var that = this;
      //获取地图中心,并且改变经纬度,其中""里面是map地图的id
      this.mapCtx = wx.createMapContext("map4select");
      //将中心坐标赋值
      this.mapCtx.getCenterLocation({
        type: 'gcj02',
        success: function (res) {
          that.setData({
            latitude: res.latitude,
            longitude: res.longitude,
          })
        }
      });
      //解析成准确地址
      wxMap.reverseGeocoder({
        location: {
          latitude: that.data.latitude,
          longitude: that.data.longitude
        },
        success: function (res) {
          that.setData({
            reallAddress: res.result.address
          })
        },
        fail: function (res) {

        },
      })
    }
  },
  //点击返回之后立刻将经纬坐标转换成本人的坐标,后产生回溯效果
  my_location: function (e) {
    var that = this;
    that.onLoad();
  },
  Location: function () {
    var that = this;
    wx.getLocation({
      type: "wgs84",
      success: function (res) {
        that.setData({
            latitude: res.latitude,
            longitude: res.longitude
          }),
          //逆解析,将经纬坐标转化成准确坐标
          wxMap.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            success: function (res) {
              that.setData({
                reallAddress: res.result.address
              })
            },
            fail: function (res) {

            },
          })
      }
    });

  },
  //点击确认后将地址赋值给全局数据,以便tabbar页面可以直接调用
  clickbutton:function(){
    wx.switchTab({
      url: '../../pages/publish/publish',
    })
    var app = getApp();
    app.globalData.address=this.data.reallAddress
  }
})